﻿using System;
using TMPro;
using UnityEngine;

namespace Yoozoo.Gameplay.Managers
{
    [RequireComponent(typeof(TMP_Text))]
    [DisallowMultipleComponent]
    public class TextMeshProLocalizationProvider : MonoBehaviour
    {
        private TMP_Text text;

        public static Action<string, Action<TMP_FontAsset>> localizationProvider;

        private string fontName;
        //更改语言不要更改材质球
        public Material originMat;
        private MeshRenderer meshRender;
        
        private void Awake()
        {
            text = GetComponent<TMP_Text>();
            meshRender = GetComponent<MeshRenderer>();
        }

        private void SetFontAsset(TMP_FontAsset fontAsset)
        {
            if (originMat != null && fontAsset != null && text.font != fontAsset)
            {
                text.font = fontAsset;
                //tmp如果出现多图集会自动生成一个SubMesh,所以我们只需要去管理mainTexture
            }

#if UNITY_EDITOR
            //editor下使用实例材质
            if (originMat != null)
            {
                //材质不相同,更换材质,如果贴图也不同,更换贴图,Editor下,更换材质使用实例化的材质,防止更改影响原本的材质球
                if (text.fontSharedMaterial.name != originMat.name)
                {
                    text.fontMaterial = originMat;
                    if (text.fontMaterial.mainTexture != fontAsset.atlasTexture)
                    {
                        text.fontMaterial.mainTexture = fontAsset.atlasTexture;
                    }
                }
                else
                {
                    //如果材质相同,贴图不同,则更换贴图
                    if (text.fontSharedMaterial.mainTexture != fontAsset.atlasTexture)
                    {
                        text.fontMaterial.mainTexture = fontAsset.atlasTexture;
                    }
                }
            }
            
#else 
            if (originMat != null && originMat.mainTexture != fontAsset.atlasTexture)
            {
                originMat.mainTexture = fontAsset.atlasTexture;
            }
            if (originMat != null && text.fontSharedMaterial.name != originMat.name)
            {
                text.fontSharedMaterial = originMat;
            }
#endif
        }

        public void UpdateLocalizationFont()
        {
            if (text == null || text.font == null)
                return;

            if (string.IsNullOrEmpty(fontName))
            {
                fontName = text.font.name;
            }
            
            localizationProvider?.Invoke(fontName, SetFontAsset);
        }

        private void OnEnable()
        {
            if (Application.isPlaying)
            {
                if (originMat != null)
                {
                    UpdateLocalizationFont();
                }
            }
        }
    }
}
